<?php

class Users_AddAction extends SrsUsersBaseAction
{
	public function getCredentials()
	{
		return 'users.add';
	}

	public function handleError(AgaviRequestDataHolder $rd)
	{
		$this->setAttribute('roles', $this->getAvailableRoles());

		return 'Error';
	}

	public function executeRead()
	{
		$this->setAttribute('roles', $this->getAvailableRoles());

		return 'Input';
	}

	public function executeWrite(AgaviRequestDataHolder $rd)
	{
		$userData = $rd->getParameter('user');

		if (!array_key_exists($userData['role'], $this->getAvailableRoles()))
		{
			$this->addError('unknown_role', 'user[role]', 'Podana rola nie istnieje.');

			return 'Error';
		}

		$user = new User();
		$user->email    = $userData['email'];
		$user->password = hash('sha256', $userData['password']);
		$user->role     = $userData['role'];
		$user->name     = $userData['name'];
		$user->active   = true;
		$user->phone    = $userData['phone'];

		try
		{
			$user->save();
		}
		catch (Exception $x)
		{
			$this->addError('email_taken', 'user[email]', 'Podany adres e-mail już jest wykorzystany.');

			return 'Error';
		}

		$this->setAttribute('user', $user->id);

		return 'Success';
	}

	private function getAvailableRoles()
	{
		return $this->getContext()->getUser()->getAvailableRoles();
	}
}